package com.yzdbx.individualtask;

import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SalesOrderDetailReGen {
    /**
     * 主程序入口
     * 该方法主要用于批量插入销售订单明细数据
     * 它首先获取数据库连接，然后查询所有订单ID和产品ID
     * 接着，它会生成随机的订单明细数据，并批量插入数据库中
     * 最后，确保数据库连接的自动提交属性被恢复，并关闭连接
     *
     * @param args 命令行参数
     * @throws Exception 如果数据库操作失败
     */
    public static void main(String[] args) throws Exception {
        // 获取数据库连接
        Connection connection = DbUtil.getConnection();
        // 保存原始的自动提交状态
        boolean originalAutoCommit = true;
        try {
            // 获取并设置连接的自动提交状态为false，以便手动控制事务
            originalAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);

            // 查询所有主表订单ID
            List<Integer> orderIds = new ArrayList<>();
            try (Statement stmt = connection.createStatement();
                 ResultSet rs = stmt.executeQuery("SELECT id FROM salesOrders")) {
                while (rs.next()) {
                    orderIds.add(rs.getInt("id"));
                }
            }

            // 查询所有产品ID（与原逻辑一致，只选产成品）
            List<Integer> productIds = new ArrayList<>();
            try (PreparedStatement statement = connection.prepareStatement("select id from gy02ProductRepository where productClassification = '产成品'");
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    productIds.add(resultSet.getInt("id"));
                }
            }

            // 获取明细表最大ID
            int detailMaxId = getMaxId(connection, "xs02SalesOrderBreakdown");

            // 准备插入明细数据的SQL语句
            String detailSql = "insert into xs02SalesOrderBreakdown (id,productInformation,number,associatedSalesOrders,unitPrice,quantityOfShipments,numberOfRemainingShipments,amount) values (?,?,?,?,?,?,?,?)";
            try (PreparedStatement detailStatement = connection.prepareStatement(detailSql)) {
                int batchCount = 0;
                final int BATCH_SIZE = 100;

                // 遍历每个订单ID，生成并插入明细数据
                for (Integer orderId : orderIds) {
                    // 明细产品ID去重且高效
                    int detailCount = RandomUtil.randomInt(1, 4);
                    List<Integer> shuffledProductIds = new ArrayList<>(productIds);
                    Collections.shuffle(shuffledProductIds);

                    // 为每个订单生成随机数量的明细
                    for (int j = 0; j < detailCount; j++) {
                        int curDetailId = ++detailMaxId;
                        int productId = shuffledProductIds.get(j);
                        int number = RandomUtil.randomInt(2, 3000);
                        BigDecimal unitPrice = RandomUtil.randomBigDecimal(BigDecimal.ONE, BigDecimal.valueOf(20)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(number)).setScale(2, BigDecimal.ROUND_HALF_UP);

                        // 设置SQL语句参数
                        detailStatement.setInt(1, curDetailId);
                        detailStatement.setInt(2, productId);
                        detailStatement.setInt(3, number);
                        detailStatement.setInt(4, orderId);
                        detailStatement.setBigDecimal(5, unitPrice);
                        detailStatement.setInt(6, number);
                        detailStatement.setInt(7, 0);
                        detailStatement.setBigDecimal(8, amount);
                        // 添加到批处理中
                        detailStatement.addBatch();

                        batchCount++;
                        // 当批处理达到设定大小时，执行批处理并提交事务
                        if (batchCount >= BATCH_SIZE) {
                            detailStatement.executeBatch();
                            connection.commit();
                            batchCount = 0;
                        }
                    }
                }
                // 如果还有未执行的批处理，执行并提交事务
                if (batchCount > 0) {
                    detailStatement.executeBatch();
                    connection.commit();
                }
            }
            System.out.println("销售明细表数据补全完成！");
        } finally {
            // 无论是否发生异常，都恢复自动提交状态并关闭数据库连接
            try {
                connection.setAutoCommit(originalAutoCommit);
            } catch (SQLException ignore) {}
            DbUtil.closeConnection(connection);
        }
    }

    private static int getMaxId(Connection connection, String table) throws SQLException {
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT MAX(id) FROM " + table)) {
            if (rs.next()) {
                return rs.getInt(1);
            }
        }
        return 0;
    }
} 